package com.batchengine.task;

import static com.batchengine.task.TaskStatus.*;
import static com.batchengine.util.LoggingFactory.createLogger;
import com.batchengine.Definitions;
import org.apache.log4j.Logger;

/**
 * Created by sunil.incubator@yahoo.com.
 * User: sunil.kalva
 * Date: Jun 22, 2009
 */
public abstract class DefaultTask extends Task {

    private TaskStatus taskStatus;
    private TaskProcessingType processingType;
    private static final Logger logger = createLogger();

    private String name;
    private boolean errorOccured = false;

    protected DefaultTask(String name) {
        this.name = name;
    }

    public TaskProcessingType getProcessingType() {
        return processingType;
    }

    public void setProcessingType(TaskProcessingType processingType) {
        this.processingType = processingType;
    }

    public boolean isErrorOccured() {
        return errorOccured;
    }

    public String getName() {
        return name;
    }

    protected void beforeExecute() {
        logger.debug("before execute " + getName());
    }

    protected void executeTask(TaskContext context) {

        try {

            setTaskStatus(READY);
            beforeExecute();

            setTaskStatus(RUNNING);
            context.addcontextParam(Definitions.ContextParams.OWNER, this);
            execute(context);

            setTaskStatus(SUCCESS);
            afterExecute();
        } catch (Exception e) {
            logger.error("error@DefaultTask#execute", e);
            errorOccured = true;
            setTaskStatus(FAILED);
            handleError();
        } finally {
            cleanup();
            if (!errorOccured) {
                setTaskStatus(COMPLETED);
            }
        }
    }

    protected void afterExecute() {
        logger.debug("after execute " + Thread.currentThread().getName());
    }

    protected void handleError() {
        logger.error("handleError " + getName());
    }

    protected void cleanup() {
        logger.debug("cleanup " + Thread.currentThread().getName());
    }


    public TaskStatus getTaskStatus() {
        return taskStatus;
    }

    public void setTaskStatus(TaskStatus taskStatus) {
        this.taskStatus = taskStatus;
    }

    public abstract void execute(TaskContext context);
}
